#!/usr/bin/env bash

SERVER_NAME=rabbitmq
IMAGE_NAME=rabbitmq
VERSION=3.13.6-management
PORT=5672
PORT_MANAGEMENT=15672
DIR=/home/app/$SERVER_NAME

if [ -d "./Dockerfile" ]; then
  echo "Find Dockerfile.Will build docker images."
  docker build -t $IMAGE_NAME:$VERSION ./
fi

if [ ! -d "$DIR" ]; then
  mkdir -p $DIR;
  echo "dir $DIR create successful."
else
  echo "dir $DIR already exist.Will use it."
fi

echo "remove old container"

EM_RUN=$(docker ps| grep $SERVER_NAME|awk 'NR==1'|awk '{print $1}')
EM=$(docker ps -a | grep $SERVER_NAME|awk 'NR==1'|awk '{print $1}')

if [ -n "$EM_RUN" ]; then
  echo "container $EM_RUN is running.will stop and delete it."
  docker stop "$EM_RUN"
  docker rm "$EM_RUN"
elif [ -n "$EM" ]; then
  echo "container $EM is stop,but container is exists,will only delete it."
  docker rm "$EM"
else
  echo "Not find container $SERVER_NAME"
fi

# KRAFT 模式不依赖kafka
docker run -d --name $SERVER_NAME \
-p $PORT:$PORT \
-p PORT_MANAGEMENT:PORT_MANAGEMENT \
--restart=always $IMAGE_NAME:$VERSION
